package com.pig4cloud.pig.ads.controller;

import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiSnsGetuserinfoBycodeRequest;
import com.dingtalk.api.request.OapiUserGetbyunionidRequest;
import com.dingtalk.api.request.OapiV2UserGetRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiSnsGetuserinfoBycodeResponse;
import com.dingtalk.api.response.OapiUserGetbyunionidResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.taobao.api.ApiException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @Title null.java
 * @Package com.pig4cloud.pig.ads.controller
 * @Author 马嘉祺
 * @Date 2021/8/16 17:12
 * @Description 钉钉开放平台接入
 */
@Slf4j
@Controller
@RestController
@RequestMapping("/dingtalk")
@RequiredArgsConstructor
public class DingTalkController {

	@RequestMapping(value = "/login")
	public String login(@RequestBody(required = false) JSONObject json, @RequestParam("code") String code, @RequestParam("state") String state, HttpServletRequest request) {
		try {

			System.out.println(json);
			System.out.printf("code=%s, state=%s\n", code, state);

			System.out.println();

			Enumeration<String> headerNames = request.getHeaderNames();
			while (headerNames.hasMoreElements()) {
				String headerName = headerNames.nextElement();
				String headerValue = request.getHeader(headerName);
				System.out.printf("headerName=%s, headerValue=%s\n", headerName, headerValue);
			}

			System.out.println();


			// 获取access_token，注意正式代码要有异常流处理
			String access_token = getToken();

			// 通过临时授权码获取授权用户的个人信息
			DefaultDingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
			OapiSnsGetuserinfoBycodeRequest reqBycodeRequest = new OapiSnsGetuserinfoBycodeRequest();
			// 通过扫描二维码，跳转指定的redirect_uri后，向url中追加的code临时授权码
			reqBycodeRequest.setTmpAuthCode(code);
			// 修改appid和appSecret为步骤三创建扫码登录时创建的appid和appSecret
			OapiSnsGetuserinfoBycodeResponse bycodeResponse = client2.execute(reqBycodeRequest, "dingbycn7hfjny1ocker", "EnFDEnCnOign1qRhPYeESau6UWeuHTxb2k8d_iJDY-qNsmU5WDxeNl7fL4MvJ-oU");

			// 根据unionid获取userid
			String unionid = bycodeResponse.getUserInfo().getUnionid();
			DingTalkClient clientDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid");
			OapiUserGetbyunionidRequest reqGetbyunionidRequest = new OapiUserGetbyunionidRequest();
			reqGetbyunionidRequest.setUnionid(unionid);
			OapiUserGetbyunionidResponse oapiUserGetbyunionidResponse = clientDingTalkClient.execute(reqGetbyunionidRequest, access_token);
			if (oapiUserGetbyunionidResponse.getErrcode() == 60121L) {
				return bycodeResponse.getBody();
			}
			// 根据userId获取用户信息
			String userid = oapiUserGetbyunionidResponse.getResult().getUserid();
			DingTalkClient clientDingTalkClient2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
			OapiV2UserGetRequest reqGetRequest = new OapiV2UserGetRequest();
			reqGetRequest.setUserid(userid);
			reqGetRequest.setLanguage("zh_CN");
			OapiV2UserGetResponse rspGetResponse = clientDingTalkClient2.execute(reqGetRequest, access_token);
			System.out.println(rspGetResponse.getBody());
			return rspGetResponse.getBody();
		} catch (ApiException e) {
			e.printStackTrace();
			return "-1";
		}
	}

	public String getToken() {
		try {
			DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
			OapiGettokenRequest request = new OapiGettokenRequest();
			// 填写步骤一创建应用的Appkey
			request.setAppkey("dingbycn7hfjny1ocker");
			// 填写步骤一创建应用的Appsecret
			request.setAppsecret("EnFDEnCnOign1qRhPYeESau6UWeuHTxb2k8d_iJDY-qNsmU5WDxeNl7fL4MvJ-oU");
			request.setHttpMethod("GET");
			OapiGettokenResponse response = client.execute(request);
			String accessToken = response.getAccessToken();

			log.info(accessToken);

			return accessToken;
		} catch (ApiException e) {
			throw new RuntimeException();
		}
	}

}
